#include "mainwidget.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
{
    setButtons();
    setColor();
}

MainWidget::~MainWidget()
{

}
void MainWidget::setButtons()
{
    int i=0,j=0;
    mapper = new QSignalMapper;
    verticalLayout = new QVBoxLayout;
    setLayout(verticalLayout);
    verticalLayout->setSizeConstraint(QLayout::SetNoConstraint);
    for(i=0;i<3;i++)
    {
        hlayouts[i] = new QHBoxLayout();
        verticalLayout->addLayout(hlayouts[i]);
        for(j=0;j<3;j++)
        {
            buttons[i*3+j] = new QPushButton(this);     
            mapper->setMapping(buttons[i*3+j],i*3+j);
            connect(buttons[i*3+j],SIGNAL(clicked()),mapper,SLOT(map()));
            hlayouts[i]->addWidget(buttons[i*3+j]);
        }
    }
    connect(mapper,SIGNAL(mapped(int)),this,SLOT(check(int)));
}

void MainWidget::setColor()
{
    int i,choice;
    for(i=0;i<9;i++)
    {
        buttons[i]->setText("Black");
        buttons[i]->setStyleSheet("background: black");
    }
    for(i=0;i<3;i++)
    {
        choice = qrand()%3;
        buttons[i*3+choice]->setText("White");
        buttons[i*3+choice]->setStyleSheet("background: white");
    }
}

void MainWidget::updateColor()
{
    int i,choice;
    for(i=8;i>=3;i--)
    {
        buttons[i]->setText(buttons[i-3]->text());
        buttons[i]->setStyleSheet(buttons[i-3]->styleSheet());
    }
    for(i=0;i<3;i++)
    {
        buttons[i]->setText("Black");
        buttons[i]->setStyleSheet("background: black");
    }
    choice = qrand()%3;
    buttons[choice]->setText("White");
    buttons[choice]->setStyleSheet("background: white");
}

void MainWidget::check(int button_id)
{
    msg = new QMessageBox;
    if(buttons[button_id]->text() == "White")
    {
        msg->setText("you lose!");
        msg->show();
    }
    updateColor();
}
